package com.ztgf.user.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.user.models.bo.UserImBO;
import com.ztgf.user.models.vo.UserImVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.ztgf.user.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.user.mapper.UserImMapper;
import com.ztgf.user.models.service.IUserImService;
import com.ztgf.user.models.bo.UserImSaveBO;
import com.ztgf.user.models.dto.UserImDTO;

import java.util.List;

/**
 * im账号表控制器
 *
 * @author zhanghualang
 * @Date 2020-05-28 17:48:46
 */
@DubboService
public class UserImServiceImpl extends ServiceImpl<UserImMapper, UserImDTO> implements IUserImService{

    @Resource
    private YmlConfig ymlConfig;
    @DubboReference
    private IShopInfoService iShopInfoService;

    @Override
    public boolean add(UserImSaveBO saveBO) {
        UserImDTO dto = new UserImDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    @Override
    public UserImDTO getSellerByUserId(Long userId) {
        Wrapper<UserImDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userId).eq("type", 1);//类型 0买家，1卖家、2平台客服
        return this.selectOne(wrapper);
    }

    @Override
    public UserImDTO getCSbyShopId(Long shopId) {
        List<UserImDTO> userImDTOS = baseMapper.getCSbyShopId(shopId);
        ShopInfoDTO shopInfoDTO = iShopInfoService.selectById(shopId);

        if (userImDTOS != null && userImDTOS.size() > 0){
            return userImDTOS.get(0);
        }else {
            //不存在客服。获取主账号im
            return getSellerByUserId(shopInfoDTO.getUserId());
        }
    }

    @Override
    public Page<UserImVO> queryPageList(UserImBO bo) {
        Page<UserImVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<UserImVO> userImVOS = baseMapper.queryPageList(page, bo);
        page.setRecords(userImVOS);
        return page;
    }
}
